<?php

namespace App\Console\Commands;

use App\Models\Agent;
use App\Models\Order;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class RemovePersonalPerformanceFromTeamPerformance extends Command
{
    /**
     * 命令名称及签名
     *
     * @var string
     */
    protected $signature = 'migrate:remove_personal_performance_from_team_performance';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '剔除新系统团队业绩内的个人业绩';

    /**
     * 代理商总数
     * @var int
     */
    protected $agentCount = 0;

    public function handle()
    {
        try {
            $this->agentCount = Agent::query()->count();
            $bar = $this->output->createProgressBar($this->agentCount);
            $bar->start();
            Agent::query()
                ->withTrashed()
                ->select(['id'])
                ->chunk(5000, function (Collection $agents) use ($bar) {
                    $agents->each(function (Agent $agent) use ($bar) {
                        // 是否已经完成过了 (第一道判断, 省去去获取锁的消耗)
                        if (0 !== Redis::hexists('migrate:agent_decrement_team_performance', $agent['id'])) {
                            return false;
                        }

                        Cache::lock('migrate:agent_' . $agent['id'] . '_decrement_team_performance_lock', 1 * 60 * 60)
                            ->get(function () use ($agent) {
                                // 是否已经完成过了 (第二道判断, 防止有进程通过了第一道, 然后此时释放锁, 就会再一次获取锁并进入处理)
                                if (0 !== Redis::hexists('migrate:agent_decrement_team_performance', $agent['id'])) {
                                    return false;
                                }

                                try {
                                    \DB::beginTransaction();

                                    $agent
                                        ->selfSupportOrders()
                                        ->where('orders.total_amount', '>', 0) // 找大于零的, 等于零 意味着已经取消, 取消时候会扣减
                                        ->select(['id', 'agent_id', 'income', 'total_amount', 'created_at'])
                                        ->each(function (Order $order) use ($agent) {
                                            $agent->incrementOrDecrementTeamIncome($order['income'], 'decrement', $order['created_at']);
                                            $agent->incrementOrDecrementTeamPerformance($order['total_amount'], 'decrement', $order['created_at'], 1);
                                        }, 5000);

                                    \DB::commit();
                                } catch (\Exception $e) {
                                    \DB::rollBack();

                                    Redis::hset('migrate:agent_decrement_team_performance_error', $agent['id'], $e->getMessage());
                                    return false;
                                }

                                // 已完成
                                Redis::hset('migrate:agent_decrement_team_performance', $agent['id'], 0);
                                return true;
                            });

                        $bar->advance(1);
                        return true;
                    });
                });
            $bar->finish();
        } catch (\Exception $e) {
            $this->output->error($e->getMessage());
        }
    }
}
